<template>

    <div class="user-box">
        <el-row class="p-all-20 box-flex">
			<el-col :span="4">
				<el-select v-model="filterValue" placeholder="请选择">
					<el-option v-for="item in filterList" :key="item" :value="item">
					</el-option>
				</el-select>
			</el-col>
            <el-col :span="4">
                <el-input placeholder="请输入手机号 昵称 或 用户角色" v-model="keyWord" clearable></el-input>
            </el-col>
            <el-col :span="4" class="m-l-10">
                <el-button type="primary" @click="searchAdmin(1)">筛选</el-button>
                <el-button type="primary" @click="searchAdmin(2)">重置</el-button>
            </el-col>
        </el-row>
        <template>
            <el-row class="p-all-20 box-flex m-t-10">
                <el-col :span="4" >
                    <el-button type="success" @click="setNewAdmin">新建用户</el-button>
                    <el-button type="danger" @click="allDelete">批量删除</el-button>
                </el-col>
            </el-row>
            <el-table :data="adminList" @selection-change="handleSelectionChange">
                <el-table-column type="selection">
                </el-table-column>
                <el-table-column label="手机号" align="center">
                    <template slot-scope="scope">{{ scope.row.login_name }}</template>
                </el-table-column>
                <el-table-column prop="nick_name" label="昵称" ></el-table-column>
                <el-table-column prop="role_name" label="角色"  align="center"></el-table-column>
                <el-table-column prop="create_time" label="创建时间" align="center"></el-table-column>
                <el-table-column label="操作"  align="center">
                    <template slot-scope="scope">
                        <el-button @click="toAdminEditer(scope.$index,scope.row)" size='mini' type="primary">修改</el-button>
                        <el-button @click="toDeleteAdmin(scope.row)" size='mini' type="danger">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog title="新建用户" :visible.sync="centerDialogVisible" width="30%" center>
                <el-row class="p-all-20 ">
                    <el-col :span="20" class="box-flex m-b-10">
                        <span class="sp-w-50 m-r-10">手机号</span>
                        <el-input type="请输入手机号" v-model="userNumber" />
                    </el-col>
                    <el-col :span="20" class="box-flex m-b-10">
                        <span class="sp-w-50 m-r-10">昵称</span>
                        <el-input type="请输入昵称" v-model="userName" />
                    </el-col>
                    <el-col :span="20" class="box-flex m-b-10">
                        <span class="sp-w-50 m-r-10">密码</span>
                        <el-input type="请输入密码" v-model="userPassword" />
                    </el-col>
                    <el-col :span="20" class="box-flex m-b-10">
                        <span class="sp-w-50 ">角色</span>
                        <el-select v-model="roleValue" placeholder="请选择">
                            <el-option v-for="item in roleOptions" :key="item.roleName" :value="item.roleName">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveAdmin">确 定</el-button>
                </span>
            </el-dialog>


        </template>
    </div>
</template>

<script>
    import {
        SUCCESS_REQUEST_STATUS
    } from '@/utils/config.js'
	import {
			getToken
	} from '@/utils/auth'
    export default {
        props: {
            // 用户数据
            adminList: {
                default: [],
                type: Array,
                required: true
            },
            // 角色
            ruleMap: {
                default: {},
                type:[Array,Object],
                required: true
            }

        },
        data() {
            return {
                roleOptions: [], // 角色数据
                roleValue: '',
                userNumber: '',
                userName: '',
                userPassword: '',
                joinDate: '',
				userId: '',
				keyWord: '',
                centerDialogVisible: false,
				multipleSelection: [],
				filterValue: '手机号',
				filterList:['手机号','昵称','用户角色']
            }
        },
		created() {
			console.log(this.ruleMap)
		},
        methods: {
			searchAdmin(num) {
				let val = this.filterValue == '手机号' ? 'mobile': this.filterValue == '昵称' ? 'name' :'roleName'
				this.$emit('searchAdmin', num, this.keyWord,val)
			},
			allDelete() {
				console.log(this.multipleSelection)
				if(!this.multipleSelection.length) {
					this.$message({
						message: '请选择需要删除的用户',
						type: 'warning'
					});
					return
				}
				let map = this.multipleSelection.map((item) => {return item.merchant_user_id}).join(',')
				this.$confirm("确定批量删除选中用户?", "删除用户", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					this.$ajax({
						api: 'admin/batchDelete',
						params: {
							token: getToken(),
							merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '', 
							ids: map
						}
					}).then(res => {
						if(res.status === SUCCESS_REQUEST_STATUS) {
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.centerDialogVisible = false
							this.$emit('editUser')
						}
					}).catch((err) => {
						console.log(err)
						this.$message({
							message: err.message,
							type: 'warning'
						});
					})
				})
			},
			handleSelectionChange(val){
				this.multipleSelection = val
			},
			/**
			 * @desc 修改用户
			 */
			toAdminEditer(index, item) {
				console.log(item)
				this.userId = item.merchant_user_id
				this.userNumber = item.login_name
				this.userName = item.nick_name
				this.roleValue = item.role_name
				this.userPassword = item.password
				this.centerDialogVisible = true
			},
            saveAdmin() {
                let msg = !this.userNumber ? '请填写手机号' : !this.userName ? '请填写昵称' : !this.userPassword ? '请填写密码' : !this
                    .roleValue ? '请选择角色' : ''
                if (msg) {
                    this.$message({
                        message: msg,
                        type: 'warning'
                    });
                    return
                }
				let rol = ''
				console.log(this.roleValue)
				this.ruleMap.forEach((item) => {
					if(item.roleName == this.roleValue) {
						rol = item.id
					}
				})
                this.$ajax({
                    api: 'admin/save',
                    params: {
                        id: this.userId,
						token: getToken(),
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '', 
                        loginName: this.userNumber,
                        nickName: this.userName,
                        password: this.userPassword,
                        roleId: rol
                    }
                }).then(res => {
					console.log(res)
					if(res.status === SUCCESS_REQUEST_STATUS) {
						this.$message({
							message: '添加成功',
							type: 'success'
						});
						this.centerDialogVisible = false
						this.$emit('editUser')
					}
				}).catch((err) => {
					console.log(err)
					this.$message({
						message: err.message,
						type: 'warning'
					});
				})
            },
            // 删除管理员
            toDeleteAdmin(item) {
                this.$confirm("确定删除此用户?", "删除用户", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.$ajax({
                    	api: 'admin/delete',
                    	params: {
							token: getToken(),
							merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
                    		userId: item.merchant_user_id
                    	}
                    }).then(res => {
                    	if(res.status === SUCCESS_REQUEST_STATUS) {
                    		this.$message({
                    			message: '删除成功',
                    			type: 'success'
                    		});
                    		this.centerDialogVisible = false
                    		this.$emit('editUser')
                    	}
                    }).catch((err) => {
                    	console.log(err)
                    	this.$message({
                    		message: err.message,
                    		type: 'warning'
                    	});
                    })
                })
            },
            setNewAdmin() {
				this.roleOptions = this.ruleMap 
				console.log(this.roleOptions)
//                 Object.values(this.ruleMap).forEach((val) => {
//                     this.roleOptions.push({
//                         value: val
//                     })
//                 })
                this.centerDialogVisible = true
            },
            handleCurrentChange(page) {
                this.currentPage = page
            }
        }


    }
</script>

<style>
    .user-box {
        width: 100%;
        max-width: 100%;
    }
</style>
